﻿using Microsoft.EntityFrameworkCore;
using OpenAiMobile.Models;
using OpenAiMobile.Tools;

namespace OpenAiMobile.Database
{
    // ReSharper disable once IdentifierTypo
    public class SqliteDbContext : DbContext
    {
        public DbSet<ConfigModel> ConfigModels { get; set; }

        private readonly string _connectionString;

        // ReSharper disable once IdentifierTypo
        public SqliteDbContext(DbContextOptions<SqliteDbContext> options)
            : base(options)
        {
            SQLitePCL.Batteries_V2.Init();
            _connectionString = Constants.SQLite.GetConnectionString(FileSystem.Current.AppDataDirectory);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!string.IsNullOrWhiteSpace(_connectionString))
            {
                try
                {
                    optionsBuilder.UseSqlite(_connectionString);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            optionsBuilder.UseLazyLoadingProxies();

            base.OnConfiguring(optionsBuilder);
        }

        //Load the entities into EF Core
        public void LoadEntities()
        {
            Database.EnsureCreated();
            ConfigModels?.Load();
        }
    }
}
